package com.kyrie.controller;

import com.kyrie.annotation.TransLog;
import com.kyrie.dto.UserLoginDto;
import com.kyrie.security.jwt.JWTUtil;
import com.kyrie.system.druid.DatasourceSelectHelper;
import com.kyrie.system.mybatis.execption.ServiceException;
import com.kyrie.system.mybatis.service.IDefaultService;
import com.kyrie.utils.GlobalConstants;
import com.kyrie.vo.LoginReturnBean;
import com.kyrie.vo.ResponseBean;
import com.kyrie.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/***
 * 描述: 登录
 *
 * @author wuxiang
 * @date 2020-04-07 23:50
 */
@Validated
@RestController
public class loginController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "defaultService")
    private IDefaultService service;


    /**
     * 用户登录认真接口
     * @param user 用户登录信息
     * @return ResponseBean
     * @throws ServiceException
     */
    @TransLog(transCode = "/login",description = "@用户登录接口")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseBean<LoginReturnBean> login(@Valid @RequestBody UserLoginDto user) throws ServiceException {

        // 切换配置库
        DatasourceSelectHelper.setKey(DatasourceSelectHelper.CONFIG_DB);
        UserInfoVO userDb = service.selectOne(GlobalConstants.NAME_SPACE + "getUserInfo",user);
        String password = userDb.getPassword();
        String isLocked = userDb.getIsLocked();

        String token = "";
        // TODO 当前为测试demo,后续需优化数据库密码及登录校验规则，避免明文校验
        if (StringUtils.isEmpty(password)) {
            return ResponseBean.fail(null,GlobalConstants.FAIL_CODE,"用户名或密码不正确！");
        } else if (!password.equals(user.getPassword())) {
            return ResponseBean.fail(null,GlobalConstants.FAIL_CODE,"用户名或密码不正确！");
        } else if ("0".equals(isLocked)) {
            return ResponseBean.fail(null,GlobalConstants.FAIL_CODE,"账号已被锁定，请联系管理员进行解锁！");
        } else {
            token = JWTUtil.createToken(userDb);
        }
        // 登录成功返回bean
        LoginReturnBean loginReturnBean = service.selectOne(GlobalConstants.NAME_SPACE + "loginReturn",user);
        loginReturnBean.setToken(token);
        return ResponseBean.success(loginReturnBean,GlobalConstants.SUCCESS_CODE,"@用户登录认证成功");

    }
}
